package com.kjlink.widget.monitoring.schedule;

import com.kjlink.widget.monitoring.config.MonitorConfigParams;
import com.kjlink.widget.monitoring.schedule.handle.MonitorEventConsumerHandler;
import com.kjlink.widget.monitoring.schedule.handle.MonitorEventSendHandler;
import com.kjlink.widget.monitoring.schedule.handle.MonitorEventTaskHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * 描述:
 *   监控事件 定时任务
 * @author Vic.xu
 * @since 2025-08-04 14:27
 */
@Component
@Slf4j
@ConditionalOnProperty("${monitor.task.enabled:true")
public class MonitorEventSchedule {


    @Resource
    private MonitorEventTaskHandler monitorEventTaskHandler;


    @Resource
    private MonitorEventConsumerHandler monitorEventConsumer;

    @Resource
    private MonitorEventSendHandler monitorEventSendHandler;

    /**
     * 001. 从 redis 里消费 监控事件
     * FIXME  消费结束 触发一次上送任务
     */
    @Scheduled(fixedRateString = MonitorConfigParams.CONSUME_EVENT_INTERVAL,
            initialDelayString = "1",
            timeUnit = TimeUnit.MINUTES)
    public void consumerFromRedis() {
        log.info("监控事件 定时任务开始执行");
        monitorEventConsumer.consumeEventsFromRedis();
    }

    /**
     * 002. 标记过期的事件批次 定时任务
     * 默认 60分钟
     */
    @Scheduled(fixedRateString = MonitorConfigParams.EXPIRED_EVENT_TASK_INTERVAL,
            initialDelayString = "2",
            timeUnit = TimeUnit.MINUTES)
    public void expiredEventsTask() {
        monitorEventTaskHandler.markExpiredEventBatch();
    }

    /**
     * 003. 批次上送任务：按配置的间隔执行（默认5分钟）
     */
    @Scheduled(fixedRateString = MonitorConfigParams.EXPIRED_EVENT_TASK_INTERVAL,
            initialDelayString = "2",
            timeUnit = TimeUnit.MINUTES)
    public void sendBatchesTask() {
        monitorEventSendHandler.sendBatchesToThirdParty();
    }
}
